package controller

import (
	"github.com/gin-gonic/gin"
	"learn/service"
	"strconv"
	"time"
)

//记事本数据list
func MyNodeList(c *gin.Context) {
	page := c.DefaultQuery("page","1")
	pageInt,err := strconv.ParseUint(page,10,64)
	if err != nil{
		c.JSON(400, gin.H{
			"message" : "参数错误" + err.Error(),
		})
		return
	}
	if pageInt == 0{
		pageInt = 1
	}
	data := service.ContentList(pageInt)
	c.JSON(200, data)
}

//删除一条数据
func DelNode(c *gin.Context)  {
	id := c.Query("id")
	idInt,err := strconv.ParseUint(id,10,64)
	if err != nil{
		c.JSON(400, gin.H{
			"message" : "参数错误" + err.Error(),
		})
		return
	}
	status,msg := service.DelNode(idInt)
	if !status{
		c.JSON(417, gin.H{
			"message" : "操作失败：" + msg,
		})
		return
	}
	c.JSON(200, "操作成功")
	return

}

//更新一条数据
func UpdateNode(c *gin.Context)  {
	id := c.PostForm("id")
	title := c.PostForm("title")
	content := c.PostForm("content")
	idInt,err := strconv.ParseUint(id,10,64)
	if err != nil{
		c.JSON(400, gin.H{
			"message" : "参数错误" + err.Error(),
		})
		return
	}
	var updateContent = service.Content{
		Id :idInt,
		Title:   title,
		Content: content,
		Addtime: time.Now().Format("2006-01-02 15:04:05") ,
	}
	status,msg := service.UpdateNode(updateContent)
	if !status{
		c.JSON(417, gin.H{
			"message" : "操作失败：" + msg,
		})
		return
	}
	c.JSON(200, "更新成功")
	return

}

//插入一条数据
func AddNode(c *gin.Context){
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == ""{
		c.JSON(400, gin.H{
			"message" : "标题不能为空",
		})
		return
	}
	if content == ""{
		c.JSON(400, gin.H{
			"message" : "内容不能为空",
		})
		return
	}
	var createContent = service.Content{
		Title:   title,
		Content: content,
		Addtime: time.Now().Format("2006-01-02 15:04:05") ,
	}
	status,msg := service.CreateNode(createContent)
	if !status {
		c.JSON(417, gin.H{
			"message" : "操作失败：" + msg,
		})
		return
	}
	c.JSON(200, "操作成功")
	return

}